const orderModel = require('../models/Order');

// 获取用户订单
const getUserOrders = async (req, res) => {
    try {
        const userId = req.user.id;
        const orders = await orderModel.getUserOrders(userId);
        res.json(orders);
    } catch (error) {
        console.error('获取用户订单错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// 获取所有订单
const getAllOrders = async (req, res) => {
    try {
        const orders = await orderModel.getAllOrders();
        res.json(orders);
    } catch (error) {
        console.error('获取所有订单错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// 创建新订单
const createOrder = async (req, res) => {
    try {
        const userId = req.user.id;
        const { drugId, quantity } = req.body;
        const orderId = await orderModel.createOrder(userId, drugId, quantity);
        res.status(201).json({ id: orderId });
    } catch (error) {
        console.error('创建订单错误:', error);
        res.status(400).json({ message: error.message });
    }
};

// 根据 ID 获取订单
const getOrderById = async (req, res) => {
    try {
        const { id } = req.params;
        const order = await orderModel.getOrderById(id);
        if (!order) {
            return res.status(404).json({ message: '订单不存在' });
        }
        res.json(order);
    } catch (error) {
        console.error('获取订单错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// 更新订单状态
const updateOrderStatus = async (req, res) => {
    try {
        const { id } = req.params;
        const { status } = req.body;

        // 验证状态参数
        const validStatuses = ['pending', 'processing', 'completed', 'cancelled'];
        if (!status || !validStatuses.includes(status)) {
            return res.status(400).json({ message: '无效的订单状态' });
        }

        // 获取当前订单
        const order = await orderModel.getOrderById(id);
        if (!order) {
            return res.status(404).json({ message: '订单不存在' });
        }

        // 验证状态转换
        const currentStatus = order.status;
        const validTransitions = {
            'pending': ['processing', 'cancelled'],
            'processing': ['completed', 'cancelled'],
            'completed': [],
            'cancelled': []
        };

        if (!validTransitions[currentStatus].includes(status)) {
            return res.status(400).json({ 
                message: `不允许从 ${currentStatus} 状态转换到 ${status} 状态` 
            });
        }

        // 更新状态
        const success = await orderModel.updateOrderStatus(id, status);
        if (!success) {
            return res.status(500).json({ message: '更新订单状态失败' });
        }

        res.json({ 
            message: '订单状态更新成功',
            order: await orderModel.getOrderById(id)
        });
    } catch (error) {
        console.error('更新订单状态错误:', error);
        res.status(500).json({ message: error.message || '服务器错误' });
    }
};

// 删除订单
const deleteOrder = async (req, res) => {
    try {
        const { id } = req.params;
        const success = await orderModel.deleteOrderById(id);
        if (!success) {
            return res.status(404).json({ message: '订单不存在' });
        }
        res.json({ message: '订单删除成功' });
    } catch (error) {
        console.error('删除订单错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
};

module.exports = {
    getUserOrders,
    getAllOrders,
    getOrderById,
    createOrder,
    updateOrderStatus,
    deleteOrder
};